package cn.itcast.controller;


import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.ModuleService;
import cn.itcast.service.system.UserService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController{


    @Autowired
    HttpServletRequest request;
    @Autowired
    private HttpSession session;

    @Autowired
    private UserService userService;

    @Autowired
    private ModuleService moduleService;
	@RequestMapping("/login")
	public String login(String email,String password) {
        //1 email和密码不能为空
        if (StringUtils.isEmpty(email)||StringUtils.isEmpty(password)) {
            request.setAttribute("error","用户名和密码不能为空");
            return "forward:/login.jsp";
        }

        //使用shiro认证
        /*
        * 1 创建令牌
        * 2获取主题
        * 3开始认证
        * */
        password = new Md5Hash(password,email,2).toString();
        //1创建令牌
        UsernamePasswordToken token = new UsernamePasswordToken(email, password);

        //2 获取主题
        Subject subject = SecurityUtils.getSubject();

        //3 开始认证
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            request.setAttribute("error","邮箱或者密码错误");
            return "forward:/login.jsp";   //使用forward   保证使用的是同一个request
        }

        //从shiro中获取当前登录人
        User user = (User) subject.getPrincipal();

        // 把登录人的信息放入session域中
        session.setAttribute("loginUser",user);

        //动态构造菜单  根据用户所属不同展示不同的菜单
        List<Module> moduleList =  moduleService.findModulesByUser(user);
        session.setAttribute("modules",moduleList);

		return "home/main";
	}


    //退出
    @RequestMapping(value = "/logout",name="用户登出")
    public String logout(){

        // session.removeAttribute("loginUser");

        SecurityUtils.getSubject().logout();   //登出

        return "forward:login.jsp";
    }

    @RequestMapping("/home")
    public String home(){
	    return "home/home";
    }
}
